from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import Users
from finance.models import Article, Category
from uuid import uuid4
from datetime import datetime
import os
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

'''
查询文章列表
带分页功能
'''


def home(request):
    articles = Article.objects.all()
    paginator = Paginator(articles, 3)  # 每页显示3条数据
    page = request.GET.get('page')  # 获取请求的页数
    try:
        articles = paginator.page(page)  # 获取当前页数的数据列表
    except PageNotAnInteger:  # 如果返回的页码不是数字(空值),返回第一页
        articles = paginator.page(1)
    except EmptyPage:  # 如果页数超出范围,返回最后一页
        articles = paginator.page(paginator.num_pages)
    return render(request, "index.html", {"articles": articles, })


'''
注册用户
'''


def register(request):
    if request.session.has_key("s_name_001"):
        return HttpResponseRedirect("/")
    if request.method == "POST":
        username = request.POST["username"]
        pwd = request.POST["password"]
        email = request.POST["email"]
        nick = request.POST["nickname"]
        Users.objects.create(username=username, password=pwd, email=email,
                             nickname=nick)
        return HttpResponseRedirect("/login")
    return render(request, "register.html")


'''
用户登录
'''


def login(request):
    if request.session.has_key("s_name_001"):
        return HttpResponseRedirect("/")
    if request.method == "POST":
        name = request.POST["username"]
        pwd = request.POST["password"]
        islogin = Users.objects.filter(username__exact=name, password__exact=pwd)
        if islogin:
            request.session["s_name_001"] = name
            return HttpResponseRedirect("/")
        else:
            return HttpResponse("登录失败")
    return render(request, "login.html")


'''
用户注销
'''


def logout(request):
    del request.session["s_name_001"]
    return HttpResponseRedirect("/")


'''
根据文章ID,展示文章详细信息
'''


def article(request, id):
    cur_article = list(Article.objects.filter(id=id).values("id", "author",
                                                            "title", "content",
                                                            "publish_date", "image"))[0]
    return render(request, "detail.html", {"article": cur_article, })


'''
发布文章
'''


def post(request):
    if request.session.has_key('s_name_001') is False:
        return HttpResponseRedirect('/login')
    cate = Category.objects.values("id", "c_name")
    user = list(Users.objects.filter(username=request.session['s_name_001']).values())[0]
    user_id = user["id"]
    author = user["nickname"]
    isadmin = user["is_admin"]
    if not isadmin:
        return HttpResponseRedirect("/")
    if request.method == "POST":
        content = request.POST["content"]
        c_id = request.POST["cateid"]
        title = request.POST["title"]
        image_name = str(request.FILES["image"])
        image_file = request.FILES["image"]
        rename_image = image_rename(image_name)
        path = "../static/images/" + rename_image
        if not os.path.exists(path):
            os.makedirs(path)
        with open(path, "wb+") as fh:
            for i in image_file.chunks():
                fh.write(i)
        Article.objects.create(title=title, content=content, c_id=c_id,
                               user_id=user_id, author=author, image=rename_image)
        return HttpResponseRedirect('/')
    return render(request, "post.html", {"category": cate})


'''
重命名上传的图片名称
'''


def image_rename(filename):
    ext = filename.split('.')[-1]
    filename = '{}.{}'.format(uuid4().hex, ext)
    year = datetime.now().year
    month = datetime.now().month
    day = datetime.now().day
    return "newsphoto/{0}/{1}/{2}/{3}".format(year, month, day, filename)